<?php

namespace plugin\admin\app\controller;

use plugin\admin\app\common\fast\Date;
use plugin\admin\app\common\Util;
use plugin\admin\app\constant\v1\CommonConstant;
use plugin\admin\app\model\User;
use plugin\admin\app\service\v1\OptionService;
use plugin\admin\app\service\v1\UserService;
use support\exception\BusinessException;
use support\Request;
use support\Response;
use Throwable;
use Workerman\Worker;

class IndexController
{

    /**
     * 无需登录及鉴权的方法
     * @var array
     */
    protected $noNeedLogin = ['index', 'index_2', 'statistics'];

    /**
     * 需要登录无需权的方法
     * @var array
     */
    protected $noNeedAuth = ['dashboard'];

    /**
     * 后台主页
     * @param Request $request
     * @return Response
     * @throws BusinessException|Throwable
     */
    public function index(Request $request): Response
    {
        clearstatcache();
        if (!is_file(base_path('plugin/admin/config/database.php'))) {
            return raw_view('index/install');
        }
        $admin = admin();
        if (!$admin) {
            $config = OptionService::getConfig();
            $title = $config['logo']['title'];
            $logo = $config['logo']['image'];
            return raw_view('account/login', ['logo' => $logo, 'title' => $title]);
        }
        if ($admin['user_status'] != CommonConstant::DEFAULT_1) {
            if ($admin['ident_type'] == CommonConstant::DEFAULT_0) {
                $config = OptionService::getConfig();
                return raw_view('account/ident', ['admin' => $admin, 'config' => $config]);
            }

            $parent_user_info = UserService::getParentUserInfo($admin);
            $admin['parent_user_info'] = $parent_user_info;
        }

        return raw_view('index/index', compact('admin'));
    }

    public function index_2(Request $request): Response
    {
        clearstatcache();
        if (!is_file(base_path('plugin/admin/config/database.php'))) {
            return raw_view('index/install');
        }
        $admin = admin();
        if (!$admin) {
            $invitation = $request->get('invitation', '');
            $link_id = $request->get('link_id', '');
            return raw_view('account/login_user', ['invitation' => $invitation, 'link_id' => $link_id]);
        }

        $parent_user_info = UserService::getParentUserInfo($admin);
        $admin['parent_user_info'] = $parent_user_info;
        return raw_view('index/index', compact('admin'));
    }

    /**
     * 仪表板
     * @param Request $request
     * @return Response
     * @throws Throwable
     */
    public function dashboard(Request $request): Response
    {
        $admin = admin();
        if ($admin['user_status'] != CommonConstant::DEFAULT_1) {
            return raw_view('index/userindex');
        }

        $db = Util::db();

        $start = Date::unixtime('month');
        $end = Date::unixtime('month', 0, 'end');

        // 用户注册
        // 今日注册
        $user_count_today = $db->table('wa_admins')
            ->where('user_status', CommonConstant::DEFAULT_2)
            ->where('created_at', '>=', date('Y-m-d') . ' 00:00:00')
            ->count('id');
        // 3天内注册
        $user_count_day3 = $db->table('wa_admins')
            ->where('user_status', CommonConstant::DEFAULT_2)
            ->where('created_at', '>=', date('Y-m-d', time() - 3 * 24 * 60 * 60) . ' 00:00:00')
            ->count('id');
        // 7天内注册
        $user_count_day7 = $db->table('wa_admins')
            ->where('user_status', CommonConstant::DEFAULT_2)
            ->where('created_at', '>=', date('Y-m-d', time() - 7 * 24 * 60 * 60) . ' 00:00:00')
            ->count('id');
        // 30天内注册
        $user_count_day30 = $db->table('wa_admins')
            ->where('user_status', CommonConstant::DEFAULT_2)
            ->where('created_at', '>=', date('Y-m-d', time() - 30 * 24 * 60 * 60) . ' 00:00:00')
            ->count('id');
        // 总用户数
        $user_count = $db->table('wa_admins')
            ->where('user_status', CommonConstant::DEFAULT_2)
            ->count('id');
        // 今日注册
        $user_login_today = $db->table('wa_admins')
            ->where('user_status', CommonConstant::DEFAULT_2)
            ->where('login_at', '>=', date('Y-m-d') . ' 00:00:00')
            ->count('id');

        // 充值
        // 充值类型金额
        $recharge_group = $db->table('wa_v1_user_recharge')
            ->where('status', CommonConstant::DEFAULT_1)
            ->select('pay_type', $db->raw('sum(payamount) as pay_amount'))
            ->groupBy('pay_type')
            ->get()
            ->keyBy('pay_type');
        $recharge_type_list = CommonConstant::get_recharge_type_list();
        $recharge_amount = 0; // // 总充值金额
        $recharge_data = [];
        foreach ($recharge_type_list as $key => $value) {
            $recharge = $recharge_group->get($key);
            $pay_amount = $recharge->pay_amount ?? '0.00';
            $recharge_data[] = [
                'pay_type' => $key,
                'pay_type_text' => $value,
                'pay_amount' => $pay_amount,
            ];
            $recharge_amount = bcadd($recharge_amount, $pay_amount, 2);
        }

        // 提现
        // 提现状态金额
        $withdrawal_group = $db->table('wa_v1_user_withdrawal')
            ->select('status', $db->raw('sum(payamount) as pay_amount'))
            ->groupBy('status')
            ->get()
            ->keyBy('status');
        $withdrawal_status_list = CommonConstant::get_withdrawal_status_list();
        $withdrawal_data = [];
        foreach ($withdrawal_status_list as $key => $value) {
            $withdrawal = $withdrawal_group->get($key);
            $pay_amount = $withdrawal->pay_amount ?? '0.00';
            $withdrawal_data[] = [
                'pay_type' => $key,
                'pay_type_text' => $value,
                'pay_amount' => $pay_amount,
            ];
        }

        return raw_view('index/dashboard', [
            'user_count_today' => $user_count_today,
            'user_count_day3' => $user_count_day3,
            'user_count_day7' => $user_count_day7,
            'user_count_day30' => $user_count_day30,
            'user_count' => $user_count,
            'user_login_today' => $user_login_today,
            'recharge_amount' => $recharge_amount,
            'recharge_data' => $recharge_data,
            'withdrawal_data' => $withdrawal_data,
        ]);
    }

    public function statistics(Request $request): Response
    {
        if ($request->method() === 'POST') {
            $created_at = $request->input('created_at');
            $type = $request->input('type');
            if(!$created_at){
                $created_at = date('Y');
            }

            $db = Util::db();
            $created = [$created_at . '-01-01 00:00:00', $created_at . '-12-31 23:59:59'];

            switch ($type){
                case 'user':
                    $list = $db->table('wa_admins')
                        ->where('user_status', CommonConstant::DEFAULT_2)
                        ->whereBetween('created_at',$created)
                        ->select([$db->raw("date_format(created_at, '%Y-%m') as time"), $db->raw('count(id) as total')])
                        ->groupBy('time')
                        ->get()
                        ->toArray();
                    break;
                case 'recharge':
                    $list = $db->table('wa_v1_user_recharge')
                        ->where('status', CommonConstant::DEFAULT_1)
                        ->whereBetween('paytime',$created)
                        ->select([$db->raw("date_format(paytime, '%Y-%m') as time"), $db->raw('sum(payamount) as total')])
                        ->groupBy('time')
                        ->get()
                        ->toArray();
                    break;
                case 'withdrawal':
                    $list = $db->table('wa_v1_user_withdrawal')
                        ->where('status', CommonConstant::DEFAULT_2)
                        ->whereBetween('audit_time',$created)
                        ->select([$db->raw("date_format(audit_time, '%Y-%m') as time"), $db->raw('sum(payamount) as total')])
                        ->groupBy('time')
                        ->get()
                        ->toArray();
                    break;
            }

            $column = $this->getMonthYear($created_at);
            $columns = array_fill_keys($column, 0);
            foreach ($list as $val) {
                $columns[$val->time] = $val->total;
            }
            $data = $this->getData($column, $columns);
            return json(['code' => 0, 'msg' => '用户分析', 'data' => $data]);

        }
    }

    // 获取 指定年 以月为单位 的数组
    public function getMonthYear($create_time)
    {
        $column = [];
        for ($i = 1; $i <= 12; $i++) {
            $month = $i;
            if ($month < 10) {
                $month = '0' . $month;
            }
            $column[] = $create_time . '-' . $month;
        }
        return $column;
    }

    public function getData($column, $columns)
    {
        $xAxisData = $column;
        $seriesData = [];
        foreach ($column as $key => $item) {
            if (array_key_exists($item, $columns)) {
                $count = $columns[$item];
                $seriesData[] = $count;
            }
        }
        $data['xAxisData'] = $xAxisData;
        $data['seriesData'] = $seriesData;
        return $data;
    }

    public function dashboard1(Request $request): Response
    {
        $admin = admin();
        if ($admin['user_status'] != CommonConstant::DEFAULT_1) {
            return raw_view('index/userindex');
        }

        // 今日新增用户数
        $today_user_count = User::where('created_at', '>', date('Y-m-d') . ' 00:00:00')->count();
        // 7天内新增用户数
        $day7_user_count = User::where('created_at', '>', date('Y-m-d H:i:s', time() - 7 * 24 * 60 * 60))->count();
        // 30天内新增用户数
        $day30_user_count = User::where('created_at', '>', date('Y-m-d H:i:s', time() - 30 * 24 * 60 * 60))->count();
        // 总用户数
        $user_count = User::count();
        // mysql版本
        $version = Util::db()->select('select VERSION() as version');
        $mysql_version = $version[0]->version ?? 'unknown';

        $day7_detail = [];
        $now = time();
        for ($i = 0; $i < 7; $i++) {
            $date = date('Y-m-d', $now - 24 * 60 * 60 * $i);
            $day7_detail[substr($date, 5)] = User::where('created_at', '>', "$date 00:00:00")
                ->where('created_at', '<', "$date 23:59:59")->count();
        }

        return raw_view('index/dashboard', [
            'today_user_count' => $today_user_count,
            'day7_user_count' => $day7_user_count,
            'day30_user_count' => $day30_user_count,
            'user_count' => $user_count,
            'php_version' => PHP_VERSION,
            'workerman_version' => Worker::VERSION,
            'webman_version' => Util::getPackageVersion('workerman/webman-framework'),
            'admin_version' => config('plugin.admin.app.version'),
            'mysql_version' => $mysql_version,
            'os' => PHP_OS,
            'day7_detail' => array_reverse($day7_detail),
        ]);
    }

}
